package com.algorithm.search;

/**
 * 二分查找
 *
 * @Author _G5niusX
 * @Date 2018/4/27 11:50
 */
public class BinarySearch {
    /**
     * 查找key再数组中的位置,不存在则返回-1，数组必须是有序数组
     *
     * @param key
     * @param a
     * @return
     */
    public static int rank(int key, int[] a) {
        int index = 0;
        int i = a.length - 1;
        while (index <= i) {
            int mid = index + (i - index) / 2;
            if (key < a[mid]) {
                i = mid - 1;
            } else if (key > a[mid]) {
                i = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
